package com.meelive.ingkee.iknetwork.diagnose.repo

import com.meelive.ingkee.iknetwork.diagnose.api.DiagnoseApiException
import com.meelive.ingkee.iknetwork.diagnose.model.IKNetworkDiagnoseConfig
import com.meelive.ingkee.iknetwork.diagnose.model.IKNetworkDiagnoseResult
import com.meelive.ingkee.network.http.OkHttpClientManager
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

object AppConfigServiceRepo {

    fun reqAppConfig(client: OkHttpClient?, host: String, url: String, key: String): Observable<IKNetworkDiagnoseConfig> {
        return  Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client ?: OkHttpClientManager.getClient())
                .baseUrl(host)
                .build()
                .create(AppConfigService::class.java)
                .reqAppConfig(url, key)
                .compose { upstream ->
                    upstream.onErrorResumeNext(
                            Function<Throwable?, ObservableSource<out IKNetworkDiagnoseResult?>?> { throwable ->
                                Observable.error(throwable)
                            })
                            .map {
                                if (it.code == 0) {
                                    it
                                } else {
                                    throw DiagnoseApiException(it.code, it.message ?: "")
                                }
                            }
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                }
                .map {
                    it.data
                }
    }
}